import { UITransform } from "cc";
import { tgxUIController } from "../../core_tgx/tgx";
import { GameUILayers } from "../../scripts/GameUILayers";
import { Layout_UIAnnouncement } from "./Layout_UIAnnouncement";
import { UserMgr } from "../scripts/UserMgr";
import { SubGameMgr } from "../scripts/SubGameMgr";

export class UIAnnouncement extends tgxUIController {
    constructor() {
        super('ui_announcement/ui_announcement', GameUILayers.HUD, Layout_UIAnnouncement);
    }

    private _maskWidth = 0;
    private _contentWidth = 0;
    protected async onCreated(): Promise<void> {
        let layout = this.layout as Layout_UIAnnouncement;


        let pos = layout.maskNode.position;
        this._maskWidth = layout.maskNode.getComponent(UITransform).width;

        layout.lblContent.node.setPosition(this._maskWidth / 2, pos.y, pos.z);

        let ret = await UserMgr.inst.rpc_GetAnnouncement(SubGameMgr.current?.id || 'lobby');
        if (ret.isSucc) {
            layout.lblContent.string = ret.res.content;
        }
        else {
            layout.lblContent.string = '获取公告失败，请联系管理员微信：TheMrKylin';
        }
        layout.lblContent.scheduleOnce(() => {
            this._contentWidth = layout.lblContent.getComponent(UITransform).width;
        }, 0.1);
    }

    protected onUpdate(dt: number): void {
        let layout = this.layout as Layout_UIAnnouncement;
        if (layout) {
            let pos = layout.lblContent.node.position;
            if (this._contentWidth && pos.x + this._contentWidth < -this._maskWidth / 2) {
                layout.lblContent.node.setPosition(this._maskWidth / 2, pos.y, pos.z);
            }
            else {
                layout.lblContent.node.setPosition(pos.x - dt * 200, pos.y, pos.z);
            }
        }
    }
}